package com.song.ejf.securityControl;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class SecurityControlInterceptor implements Interceptor {

	Log log = LogFactory.getLog(SecurityControlInterceptor.class);
	private static final long serialVersionUID = 1L;
	List<String> accessPoints = null;

	@Override
	public void destroy() {
		accessPoints = null;
	}

	@Override
	public void init() {

	}

	@SuppressWarnings("unchecked")
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Map<String, Object> sessionMap = ServletActionContext.getContext().getSession();
		if (accessPoints == null) {
			// 获取权限列表
			accessPoints = (List<String>) sessionMap.get("access");
		}
		// 获取此次调用的方法
//		String resource = invocation.getProxy().getAction().getClass().getName() + "." + invocation.getProxy().getMethod();
		HttpServletRequest request = ServletActionContext.getRequest();  
        String currentURL = request.getRequestURI(); 
        //如果请求链接为空,跳转到error.jsp
        if(StringUtils.isBlank(currentURL)){
        	ServletActionContext.getResponse().sendRedirect(ServletActionContext.getRequest().getContextPath() + "/login.jsp");
			accessPoints = null;
			return null;
        }
        //截取功能链接
        currentURL = StringUtils.substringBefore(currentURL, ".");
        String [] temp = currentURL.split("/");
        if(temp.length < 2){
        	ServletActionContext.getResponse().sendRedirect(ServletActionContext.getRequest().getContextPath() + "/login.jsp");
			accessPoints = null;
			return null;
        }
        currentURL = temp[temp.length-2] + "/" + temp[temp.length-1];
		//如果有权限，invoke。没有返回error页面。
		if(currentURL.contains("user/vCode") || currentURL.contains("user/login")){
			accessPoints = null;
			invocation.invoke();
		}
		if(sessionMap.get("username") == null){
			ServletActionContext.getResponse().sendRedirect(ServletActionContext.getRequest().getContextPath() + "/login.jsp");
			accessPoints = null;
			return null;
		}
		if(accessPoints != null && accessPoints.contains(currentURL)){
			accessPoints = null;
			invocation.invoke();
		}
		ServletActionContext.getRequest().setAttribute("errorMsg", "没有权限访问该页面！");
		return "error";
	}

}
